package com.zl_huang.example.web;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zl_huang.example.model.vo.CommonMessageResultVO;
import com.zl_huang.example.service.IUserService;
import com.zl_huang.example.util.ExcelUtils;

@Controller
public class FileUploadController {
	@Autowired
	private IUserService userService;
	
	@RequestMapping(value="toupload")
	public String toUpload(){
		return "fileupload/FileUpLoad";
	}
	@RequestMapping(value="/upload")
	public String upload(@RequestParam(value="file",required=false) MultipartFile file,HttpSession session,ModelMap model){
		if(file.getSize() > 0){
			String path = session.getServletContext().getRealPath("/");
			System.out.println(path);
			String fileName = file.getOriginalFilename();
			System.out.println(fileName);
			File targetFile = new File(path,fileName);
			if(!targetFile.exists()){
				targetFile.mkdirs();
			}
			try {
				file.transferTo(targetFile);
			} catch (IllegalStateException e) {	
				e.printStackTrace();
			} catch (IOException e) {
			
				e.printStackTrace();
			}
			model.addAttribute("message", "Upload successfully");
			return "fileupload/FileUpLoad";
			
		}else{
			model.addAttribute("message", "Please select file!");
			return "fileupload/FileUpLoad";
			
		}	
	}
	@ResponseBody
	@RequestMapping(value="/uploadFile")
	public CommonMessageResultVO uploadFile(@RequestParam(value="uploadFile") MultipartFile[] uploadFile,HttpSession session,ModelMap model){
		System.out.println("我进来了哦");
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		MultipartFile uploadSimpleFile = uploadFile[0];
		String fileName = uploadSimpleFile.getOriginalFilename();
		System.out.println(fileName);
		String postfix = fileName.substring(fileName.lastIndexOf("."));
		System.out.println(postfix);
		Map<String,String> messageMap = new HashMap<String ,String >();
		try{
		if(ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix)|| ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix) ){
			userService.saveStudentByExcel(uploadSimpleFile.getInputStream(),postfix);
			resultVO.setSuccess(true);
		}else{
			messageMap.put("message", "文件格式不正确");
			resultVO.setMessageMap(messageMap);
		}
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", "批量导入失败");
			resultVO.setMessageMap(messageMap);
			
		}
		
		return resultVO;
	}
	

}
